package schema

import (
	"strings"
	"xian-codegen/lib/context"
	"xian-server/lib/utils/transf"

	_ "github.com/go-sql-driver/mysql"
	"github.com/samber/lo"
)

var (
	tablesSchema  []TableDBSchema
	columnsSchema []ColumnDBSchema
)

// MySQLDataTypeToGoType 通过查找映射表返回对应的 Go 类型
func MySQLDataTypeToGoType(mysqlType string) string {
	mysqlType = strings.ToLower(mysqlType)
	if goType, exists := MySQLDataTypeToGoTypeMap[mysqlType]; exists {
		return goType
	}
	return "interface{}" // 默认返回 interface{} 表示未知类型
}

// TableComment 获得指定英文名表的中文名
func TableComment(ctx *context.Context, tableName string) string {
	var sql = `
      select
        t.TABLE_NAME,
        t.TABLE_COMMENT
      from
        information_schema.TABLES t
      where
        t.TABLE_SCHEMA=(select database())
	`
	dest := make([]TableDBSchema, 0)
	if len(tablesSchema) == 0 {
		ctx.Connection.Select(&dest, sql)
	} else {
		dest = tablesSchema
	}
	target, exist := lo.Find(dest, func(i TableDBSchema) bool {
		return i.TableName == tableName
	})
	if exist {
		return target.TableName
	}
	return ""
}

// TableSchema 获取库表配置
func TableSchema(ctx *context.Context, tableName string) *TableConfigItem {
	// 模块 = "_"切割的数组下标0
	mod := strings.Split(tableName, "_")[0]
	// 表名 = "_"切割的数组下标1
	table := strings.Split(tableName, "_")[1]
	// 中文名
	tableComment := TableComment(ctx, tableName)
	return &TableConfigItem{
		Opts: TableOpts{
			Mod:                 mod,
			Table:               table,
			FullTableName:       tableName,
			UpperCamelCaseTable: transf.StrToHump(tableName),
			TableComment:        tableComment,
		},
	}
}

// ColumnsSchema 获取库表列配置
// 主要设置: 英文名,注释,表名
func ColumnsDBSchema(ctx *context.Context, tableName string) map[string]ColumnDBSchema {
	sql := `
      select
        t.TABLE_NAME,t.COLUMN_NAME,t.COLUMN_COMMENT,t.TABLE_CATALOG,t.TABLE_SCHEMA,t.ORDINAL_POSITION,t.COLUMN_DEFAULT,t.IS_NULLABLE,t.DATA_TYPE,t.CHARACTER_MAXIMUM_LENGTH,t.CHARACTER_OCTET_LENGTH,t.NUMERIC_PRECISION,t.NUMERIC_SCALE,t.DATETIME_PRECISION,t.CHARACTER_SET_NAME,t.COLLATION_NAME,t.COLUMN_TYPE,t.COLUMN_KEY,t.EXTRA,t.PRIVILEGES,t.GENERATION_EXPRESSION
      from information_schema.COLUMNS t
      where
        t.table_schema = (select database())
      order by t.ORDINAL_POSITION
	`
	dest := make([]ColumnDBSchema, 0)
	if len(columnsSchema) == 0 {
		if err := ctx.Connection.Select(&dest, sql); err != nil {
			panic(err)
		}

	} else {
		dest = columnsSchema
	}
	columns := lo.Filter(dest, func(i ColumnDBSchema, _ int) bool {
		return i.TableName == tableName
	})
	target := lo.KeyBy(columns, func(i ColumnDBSchema) string {
		return i.ColumnName
	})
	return target
}

// ColumnsRuleSchema 获取列规则配置
func ColumnsRuleSchema(columns map[string]ColumnDBSchema) map[string]TableColumn {
	var records []TableColumn
	for _, column := range columns {
		tableColumn := TableColumn{ColumnDBSchema: column}
		COLUMN_SCHEMA_GENERATOR.Handler(tableColumn, &records)
	}
	target := lo.KeyBy(records, func(i TableColumn) string {
		return i.ColumnName
	})
	return target
}

// ColumnsExSchema 获取列额外配置
func ColumnsExSchema(columns *map[string]TableColumn) {
	for key, column := range *columns {
		// 源码使用字段名称
		column.SrcProps = transf.StrToHump(column.ColumnName)
		// 源码类型
		column.SrcType = MySQLDataTypeToGoType(column.DataType)
		// 重要：更新映射中的原始条目
		(*columns)[key] = column
	}
}
